<?php

namespace App\Http\Controllers\Api;

use App\Common\Libs\Json;
use App\Consts\ExceptionCode;
use App\Http\Controllers\BaseController;
use App\Models\Cache\Cache;
use Illuminate\Http\Request;

/**
 * [!] 临时缓存读写， 管理后台迁移完成后会被删除
 * Class TempController
 * @package App\Http\Controllers\Api
 */
class TempController extends BaseController
{

    /**
     * 获取 Cache 缓存
     * 参数： key + type
     * @param Request $request
     * @return string
     */
    public function getCache(Request $request)
    {
        $params = $request->all();
        $key = $params['key'] ?? '';
        $type = $params['type'] ?? '';
        if (empty($key)) return $this->apiReturn('', ExceptionCode::ILLEGAL_PARAMETER);
        if ('string' === $type) {
            $data = Cache::getInstance()->get($key);
            return $this->apiReturn($data);
        } elseif ('hash' === $type) {
            $data = Cache::getInstance()->hGetAll($key);
            return $this->apiReturn($data);
        }
        return $this->apiReturn('', ExceptionCode::ILLEGAL_PARAMETER);
    }

    /**
     * 设置 Cache 缓存
     * 参数： key + type
     * @param Request $request
     * @return string
     */
    public function setCache(Request $request)
    {
        $params = $request->all();
        $key = $params['key'] ?? '';
        $type = $params['type'] ?? '';
        $value = $params['value'] ?? '';
        if (empty($key)) return $this->apiReturn('', ExceptionCode::ILLEGAL_PARAMETER);
        if ('string' === $type) {
            // 'OK'
            $data = Cache::getInstance()->set($key, $value);
            return $this->apiReturn($data);
        } elseif ('hash' === $type) {
            $value = Json::decode($value);
            if ($value) {
                // 'true'
                $data = Cache::getInstance()->hset($key, $value);
                return $this->apiReturn($data);
            }
        }
        return $this->apiReturn('', ExceptionCode::ILLEGAL_PARAMETER);
    }

}
